package servlet.image;

import com.google.gson.Gson;
import bean.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.UUID;

@WebServlet(name = "UploadImageServlet", value = "/UploadImageServlet.s")
// 该注释表示该Servlet支持文件上传
@MultipartConfig
public class UploadImageServlet extends HttpServlet {
    public static final String IMAGE_PATH = "D:\\web\\web-phase-ii-project\\src\\main\\webapp\\uploads\\";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Result result;

        try {
            final Part image = request.getPart("image");
            // 提取文件后缀名
            final String suffix = image.getSubmittedFileName()
                    .replaceAll(".+(\\.\\w+)", "$1"); // 这是把 .后面的进行切割
            // 生成随机文件名
            String filename = UUID.randomUUID().toString();
            filename = filename.replaceAll("-", ""); // 这是把生成的UUID中的“-”去掉，原因未知
            filename += suffix; // 加后缀

            // 保存文件
            image.write(IMAGE_PATH + filename);
            // 构建 上传文件的 web路径
            String webpath = "/GetUpload/" + filename;
            result = new Result(1, "文件上传成功", webpath);

        } catch (Exception e){
            e.printStackTrace();
            result = new Result(0, "文件上传失败", null);
        }

        final String json = new Gson().toJson(result);
        response.getWriter().append(json);
    }
}
